import React, { Component, Fragment } from 'react';
import { deleteGedan, getGedanxiangqing, editGedan, getGedanByUserId, addGedan, getUserInfo, getCollect, deleteCollect, editUser, getGedanfenlei, getTuijiansong } from '../../utils/api';
import { bus } from '../../utils/eventBus';
import '../../style/all.css';
import './My.css';

// tab栏
function qhTab (aIndex, that) {
	// 歌曲
	if (aIndex === 0) {
		return (
			<div className='s_list'>
				<h2>
					<span>id</span>
					<span>音乐标题</span>
					<span>歌手</span>
					<span>收藏</span>
				</h2>
				<ul>
					{that.state.currentCollection.map((item, index) => (
						<li onClick={() => { bus.emit('syplay', { id: item.musicid }) }} key={item.collectid}>
							<span>{index + 1}</span>
							<span>{item.music_name}</span>
							<span>{item.singer_name}</span>
							<span className='red' onClick={(e) => { that.deleteCollects(item.musicid, aIndex, e) }}>取消收藏</span>
						</li>
					))}
				</ul>
			</div>
		)
		// 歌单
	} else if (aIndex === 1) {
		return (
			<ul className='g_list'>
				{that.state.currentCollection.map((item) => (
					<li key={item.collectid} className='perse20' onClick={() => {
						window.sessionStorage.setItem('mylocation', aIndex);
						that.props.history.push(`/index/gedandetail?id=${item.gedanid}`);
					}}>
						<div className='img tophover'>
							<img width='100%' height='100%' src={"http://localhost:3001/" + item.gedan_pic_url} alt="" />
							<div className='gd_mv_hover'></div>
						</div>
						<p>{item.gedan_title}</p>
					</li>
				))}
			</ul>
		)
		// mv
	} else if (aIndex === 2) {
		return (
			<ul className='m_list'>
				{that.state.currentCollection.map((item) => (
					<li className='perse25' key={item.collectid} onClick={() => {
						window.sessionStorage.setItem('mylocation', aIndex);
						that.props.history.push(`/index/mvdetail?id=${item.mvid}`);
					}}>
						<div className='img tophover'>
							<img width='100%' height='100%' src={"http://localhost:3001/" + item.mv_pic_url} alt="" />
							<div className='gd_mv_hover'></div>
						</div>
						<p><span>{item.mv_name}</span><br /><span>{item.singer_name}</span></p>
					</li>
				))}
			</ul>
		)
	} else {
		// 创建歌单
		let {
			editGedanTitle,
			editGedanIntroduction,
			editGedanTagId,
			imgsrc3,
			showEditGedan, myCreateGedan, musicListOption, imgsrc2, showCreateGedan, gedanFenleiOption, createTitle, createIntroduction, createGedanTagId } = that.state;
		return (
			<Fragment>
				<div className='create_Gedan_btn' onClick={() => { that.createGedan(); }}>创建歌单</div>
				<div className='createmask' style={{
					display: showCreateGedan
				}}>
					<div className='create'>
						<h2>创建歌单</h2>
						<label htmlFor="g_title">标题</label><input value={createTitle} onChange={(e) => { that.changeCreateGedanVal(e, 'createTitle') }} placeholder='请输入歌单标题' type="text" name="" id="g_title" />
						<label htmlFor="">歌单类型</label>
						<select name="" id="" value={createGedanTagId} onChange={(e) => { that.changeCreateGedanVal(e, 'createGedanTagId') }}>
							{gedanFenleiOption.map((item) => (
								<option key={item.gedantagid} value={item.gedantagid}>{item.gedantag_name}</option>
							))}
						</select>
						<label htmlFor="g_introduction">歌单介绍</label><textarea value={createIntroduction} onChange={(e) => { that.changeCreateGedanVal(e, 'createIntroduction') }} name="" id="g_introduction" cols="30" rows="10" placeholder='请输入歌单介绍'></textarea>
						<label htmlFor="">选择歌曲</label>
						<ul className="checkMusic">
							{musicListOption.map((item) => (
								<li key={item.musicid}>
									<input type="checkbox" value={item.checked} onChange={(e) => { item.checked = e.target.checked }} />
									{item.music_name} -- {item.singer_name}
								</li>
							))}
						</ul>
						<label htmlFor="g_img">歌单图片</label><input onChange={() => { that.changePic() }} ref={(c) => { that.fileImg = c }} accept='image/*' type="file" name="" id="g_img" style={{ left: "-9999px", position: "absolute" }} />
						<div className='img' onClick={() => that.fileImg.click()}>
							{imgsrc2 === '' ? null : <img width="100%" height="100%" src={imgsrc2} alt="" />}
						</div>
						<div className='btns'>
							<div className='btn' onClick={() => that.create()}>创建歌单</div>
							<div className='btn' onClick={() => that.createClose()}>关闭</div>
						</div>
					</div>
				</div>
				<div className='editgedanmask' style={{
					display: showEditGedan
				}}>
					<div className='editgedan'>
						<h2>编辑歌单</h2>
						<label htmlFor="ge_title">标题</label><input value={editGedanTitle} onChange={(e) => { that.changeEditGedanVal(e, 'editGedanTitle') }} placeholder='请输入歌单标题' type="text" name="" id="ge_title" />
						<label htmlFor="">歌单类型</label>
						<select name="" id="" value={editGedanTagId} onChange={(e) => { that.changeEditGedanVal(e, 'editGedanTagId') }}>
							{gedanFenleiOption.map((item) => (
								<option key={item.gedantagid} value={item.gedantagid}>{item.gedantag_name}</option>
							))}
						</select>
						<label htmlFor="ge_introduction">歌单介绍</label><textarea value={editGedanIntroduction} onChange={(e) => { that.changeEditGedanVal(e, 'editGedanIntroduction') }} name="" id="ge_introduction" cols="30" rows="10" placeholder='请输入歌单介绍'></textarea>
						<label htmlFor="">选择歌曲</label>
						<ul className="checkMusic">
							{musicListOption.map((item) => (
								<li key={item.musicid}>
									<input type="checkbox" checked={item.checked} onChange={(e) => { item.checked = e.target.checked; that.setState({ musicListOption }) }} />
									{item.music_name} -- {item.singer_name}
								</li>
							))}
						</ul>
						<label htmlFor="ge_img">歌单图片</label><input onChange={() => { that.changeEditPic() }} ref={(c) => { that.fileEImg = c }} accept='image/*' type="file" name="" id="g_img" style={{ left: "-9999px", position: "absolute" }} />
						<div className='img' onClick={() => that.fileEImg.click()}>
							{imgsrc3 === '' ? null : <img width="100%" height="100%" src={imgsrc3} alt="" />}
						</div>
						<div className='btns'>
							<div className='btn' onClick={() => that.editGedanB()}>编辑歌单</div>
							<div className='btn' onClick={() => that.deleteGedans()}>删除歌单</div>
							<div className='btn' onClick={() => that.editClose()}>关闭</div>
						</div>
					</div>
				</div>
				<ul className='g_list'>
					{myCreateGedan.map((item) => (
						<li title="点击编辑或删除歌单" key={item.gedanid} className='perse20' onClick={() => { that.editGedans(item.gedanid) }}>
							<div className='img tophover'>
								<img width='100%' height='100%' src={"http://localhost:3001/" + item.gedan_pic_url} alt="" />
								<div className='gd_mv_hover'></div>
							</div>
							<p>{item.gedan_title}</p>
						</li>
					))}
				</ul>
			</Fragment>
		)
	}
}

export default class My extends Component {
	state = {
		// 当前激活的菜单 使用本地存储存储当前激活的菜单防止前往各个详情页之后返回没有保留状态
		activeIndex: window.sessionStorage.getItem('mylocation') !== null ? Number(window.sessionStorage.getItem('mylocation')) : 0,
		// 修改用户资料的弹框
		showEditInfo: 'none',
		// 我创建的歌单
		myCreateGedan: [],
		// 创建歌单的弹框
		showCreateGedan: 'none',
		// 修改歌单的弹框
		showEditGedan: 'none',
		userInfo: null,
		// 当前激活的收藏列表
		currentCollection: [],
		// 修改用户信息
		// id password(4-12) nickname(1-10) sex  introduction avator
		editPassWord: '',
		editNickName: '',
		editIntroduction: '',
		editAvator: null,
		editSex: '男',
		editUserid: 0,
		// imgsrc
		imgsrc: '',
		// 创建歌单
		// userid title pic musicid introduction gedantagid
		createTitle: '',
		createUserid: 0,
		createPic: null,
		createIntroduction: '',
		createGedanTagId: 0,
		// imgsrc2
		imgsrc2: '',
		gedanFenleiOption: [],
		musicListOption: [],
		// 修改歌单
		// id title pic musicid introduction gedantagid
		editGedanId: 0,
		editGedanTitle: '',
		editGedanPic: null,
		editGedanIntroduction: '',
		editGedanTagId: 0,
		// imgsrc3
		imgsrc3: '',
		// 删除歌单
		// id
		deleteGedanId: 0
	}
	componentDidMount () {
		// 获取用户详细信息
		this.getUserInfos();
		// 获取相对应的收藏
		this.getCollects(this.state.activeIndex);
	}
	changeCreateGedanVal (e, target) {
		this.setState({
			[target]: e.target.value
		})
	}
	changeEditGedanVal (e, target) {
		this.setState({
			[target]: e.target.value
		})
	}
	changePic () {
		let file = this.fileImg.files[0];
		this.setState({
			imgsrc2: URL.createObjectURL(file),
			createPic: file
		})
	}
	changeEditPic () {
		let file = this.fileEImg.files[0];
		this.setState({
			imgsrc3: URL.createObjectURL(file),
			editGedanPic: file
		})
	}
	// 取消音乐收藏
	async deleteCollects (musicid, type, e) {
		// 防止冒泡
		e.stopPropagation();
		let userid = Number(window.sessionStorage.getItem('userid'));
		let delC = await deleteCollect(userid, type, musicid);
		if (delC.status === 0) {
			window.alert(delC.message);
			// 刷新收藏
			this.getCollects(type);
		} else {
			window.alert(delC.message);
		}
	}
	// 获取用户资料
	async getUserInfos () {
		let userid = Number(window.sessionStorage.getItem('userid'));
		let info = await getUserInfo(userid);
		if (info.status === 0) {
			this.setState({
				userInfo: info.data[0]
			})
		} else {
			window.alert(info.message);
		}
	}
	// 删除歌单
	async deleteGedans () {
		if (window.confirm('此操作将永久删除该歌单, 是否继续?')) {
			// 发起请求删除
			let result = await deleteGedan(this.state.deleteGedanId);
			if (result.status === 0) {
				// 刷新我创建的歌单
				let userid = Number(window.sessionStorage.getItem('userid'));
				this.getGedanByMe(userid);
				this.setState({
					deleteGedanId: 0,
					showEditGedan: 'none'
				})
			} else {
				window.alert(result.message);
			}
		}
	}
	// 修改用户资料 准备数据
	editInfo () {
		this.setState({
			showEditInfo: 'block'
		}, async function () {
			let userid = Number(window.sessionStorage.getItem('userid'));
			let info = await getUserInfo(userid);
			if (info.status === 0) {
				this.setState({
					editNickName: info.data[0].user_nickname,
					editIntroduction: info.data[0].user_introduction,
					editSex: info.data[0].user_sex,
					editUserid: userid
				})
			} else {
				window.alert(info.message);
			}
		})
	}
	changeEditValue (e, target) {
		this.setState({
			[target]: e.target.value
		})
	}
	changeAvator () {
		let file = this.fileInput.files[0];
		this.setState({
			imgsrc: URL.createObjectURL(file),
			editAvator: file
		})
	}
	// 获取收藏
	async getCollects (type) {
		let userid = Number(window.sessionStorage.getItem('userid'));
		let collection = await getCollect(userid, type);
		if (collection.status === 0) {
			this.setState({
				currentCollection: collection.data
			})
		} else {
			window.alert(collection.message);
		}
	}
	// 切换tab 获取对应内容
	async changeTab (activeIndex) {
		if (activeIndex !== 3) {
			this.getCollects(activeIndex);
		} else {
			// 获取我创建的歌单
			let userid = Number(window.sessionStorage.getItem('userid'));
			this.getGedanByMe(userid);
		}
		this.setState({
			activeIndex
		})
	}
	// 创建歌单 数据准备
	createGedan () {
		this.getGedanfenleiOptions();
		this.getMusicListOptions();
		let userid = Number(window.sessionStorage.getItem('userid'));
		this.setState({
			showCreateGedan: 'block',
			createUserid: userid
		})
	}
	// 修改歌单 数据准备
	async editGedans (gedanid) {
		// 获取歌单详情 包含对应的音乐id
		let result = await getGedanxiangqing(gedanid);
		if (result.status !== 0) {
			window.alert(result.message);
		}
		// 获取全部音乐
		let musicList = await getTuijiansong();
		if (musicList.status !== 0) {
			window.alert(musicList.message);
		}
		// 歌单包含对应的音乐id 是一个数组
		console.log(result.data[0].gedan_music_id.split(',').map(item => Number(item)))
		// 添加全部是false的标记位
		musicList.data.forEach(item => {
			item['checked'] = false;
		})
		// 修正标记位
		result.data[0].gedan_music_id.split(',').map(item => Number(item)).forEach((item) => {
			musicList.data.forEach(item1 => {
				if (item === item1.musicid) {
					item1['checked'] = true;
				}
			})
		})
		this.getGedanfenleiOptions();
		this.setState({
			editGedanTitle: result.data[0].gedan_title,
			editGedanIntroduction: result.data[0].gedan_introduction,
			editGedanTagId: result.data[0].gedantag_id,
			showEditGedan: 'block',
			editGedanId: gedanid,
			musicListOption: musicList.data,
			deleteGedanId: gedanid
		})
		// 返回顶部
		window.scroll(0, 40);
	}
	// 获取我创建的歌单
	async getGedanByMe (userId) {
		let list = await getGedanByUserId(userId);
		if (list.status === 0) {
			this.setState({
				myCreateGedan: list.data
			})
		} else {
			window.alert(list.message);
		}
	}
	// 创建歌单
	async create () {
		let { createTitle, createUserid, createPic, createIntroduction, createGedanTagId, musicListOption } = this.state;
		let musicId = '';
		musicListOption.filter((item) => item.checked).forEach(item => musicId += (item.musicid + ','))
		musicId = musicId.substring(0, musicId.length - 1);
		// 判断是否符合规则
		if (createTitle.trim().length === 0) {
			window.alert('歌单标题不能为空！');
			return;
		}
		if (createPic === null) {
			window.alert('歌单图片不能为空！');
			return;
		}
		if (createIntroduction.trim().length === 0) {
			window.alert('歌单介绍不能为空！');
			return;
		}
		if (musicId === '') {
			window.alert('歌单歌曲不能为空！');
			return;
		}
		let formData = new FormData();
		// userid title pic musicid introduction gedantagid
		formData.set('userid', createUserid);
		formData.set('title', createTitle);
		formData.set('pic', createPic);
		formData.set('musicid', musicId);
		formData.set('gedantagid', createGedanTagId);
		formData.set('introduction', createIntroduction);
		let result = await addGedan(formData);
		if (result.status === 0) {
			window.alert('添加歌单成功！');
			// 重新获取我创建的歌单
			this.getGedanByMe(createUserid);
			this.setState({
				showCreateGedan: 'none',
				createTitle: '',
				createUserid: 0,
				createPic: null,
				createIntroduction: '',
				createGedanTagId: 0,
				createMusicId: '',
				imgsrc2: '',
				gedanFenleiOption: [],
				musicListOption: []
			})
		} else {
			window.alert(result.message);
		}
	}
	// 编辑歌单
	async editGedanB () {
		let { editGedanId,
			editGedanTitle,
			editGedanPic,
			editGedanIntroduction,
			editGedanTagId,
			musicListOption
		} = this.state;
		let musicId = '';
		musicListOption.filter((item) => item.checked).forEach(item => musicId += (item.musicid + ','))
		musicId = musicId.substring(0, musicId.length - 1);
		// // 判断是否符合规则
		if (editGedanTitle.trim().length === 0) {
			window.alert('歌单标题不能为空！');
			return;
		}
		if (editGedanIntroduction.trim().length === 0) {
			window.alert('歌单介绍不能为空！');
			return;
		}
		if (musicId === '') {
			window.alert('歌单歌曲不能为空！');
			return;
		}
		let formData = new FormData();
		// id title pic musicid introduction gedantagid
		formData.set('id', editGedanId);
		formData.set('title', editGedanTitle);
		formData.set('pic', editGedanPic);
		formData.set('musicid', musicId);
		formData.set('gedantagid', Number(editGedanTagId));
		formData.set('introduction', editGedanIntroduction);
		let result = await editGedan(formData);
		if (result.status === 0) {
			window.alert('编辑歌单成功！');
			// 重新获取我创建的歌单
			let userid = Number(window.sessionStorage.getItem('userid'));
			this.getGedanByMe(userid);
			this.setState({
				showEditGedan: 'none',
				editGedanId: 0,
				editGedanTitle: '',
				editGedanPic: null,
				editGedanIntroduction: '',
				editGedanTagId: 0,
				imgsrc3: '',
				gedanFenleiOption: [],
				musicListOption: []
			})
		} else {
			window.alert(result.message);
		}
	}
	async getGedanfenleiOptions () {
		let types = await getGedanfenlei();
		if (types.status === 0) {
			this.setState({
				gedanFenleiOption: types.data,
				createGedanTagId: types.data[0].gedantagid
			})
		} else {
			window.alert(types.message);
		}
	}
	async getMusicListOptions () {
		let musicList = await getTuijiansong();
		if (musicList.status === 0) {
			// 添加标记位
			musicList.data.forEach(item => {
				item['checked'] = false;
			})
			this.setState({
				musicListOption: musicList.data
			})
		} else {
			window.alert(musicList.message);
		}
	}
	// 关闭修改资料
	close () {
		this.setState({
			showEditInfo: 'none',
			editPassWord: '',
			editNickName: '',
			editIntroduction: '',
			editAvator: null,
			editSex: '男',
			editUserid: 0,
			imgsrc: ''
		})
	}
	// 关闭创建歌单
	createClose () {
		this.setState({
			showCreateGedan: 'none',
			createTitle: '',
			createUserid: 0,
			createPic: null,
			createIntroduction: '',
			createGedanTagId: 0,
			imgsrc2: '',
			gedanFenleiOption: [],
			musicListOption: []
		})
	}
	// 关闭编辑歌单
	editClose () {
		this.setState({
			showEditGedan: 'none',
			editGedanId: 0,
			editGedanTitle: '',
			editGedanPic: null,
			editGedanIntroduction: '',
			editGedanTagId: 0,
			imgsrc3: '',
			gedanFenleiOption: [],
			musicListOption: [],
			deleteGedanId: 0
		})
	}
	// 修改资料
	async edit () {
		let { editPassWord, editNickName, editSex, editAvator, editIntroduction, editUserid } = this.state;
		let editNTrim = editNickName.trim();
		// 校验
		if (editNTrim.trim().length > 10 || editNTrim.trim().length < 1) {
			window.alert('昵称的长度为1-10位！');
			return;
		}
		// 调用接口
		// id password(4-12) nickname(1-10) sex  introduction avator
		var formData = new FormData();
		formData.set('password', editPassWord);
		formData.set('nickname', editNTrim);
		formData.set('sex', editSex);
		formData.set('avator', editAvator);
		formData.set('introduction', editIntroduction);
		formData.set('id', editUserid);
		const info = await editUser(formData);
		if (info.status === 0) {
			window.alert('恭喜您，修改资料成功！')
			this.getUserInfos();
			this.setState({
				editPassWord: '',
				editNickName: '',
				editIntroduction: '',
				editAvator: null,
				editSex: '男',
				editUserid: 0,
				imgsrc: '',
				showEditInfo: 'none'
			})
		} else {
			window.alert(info.message);
		}
	}
	render () {
		let { activeIndex, showEditInfo, userInfo, editSex, editPassWord, editNickName, editIntroduction, imgsrc } = this.state;
		if (userInfo !== null) {
			var { user_introduction, user_nickname, user_sex, user_avator_url } = userInfo;
		}
		return (
			<div className='my'>
				<div className='editmask' style={{
					display: showEditInfo
				}}>
					<div className='editInfo'>
						<h2>修改资料</h2>
						<label htmlFor="password">密码</label><input onChange={(e) => { this.changeEditValue(e, 'editPassWord') }} value={editPassWord} placeholder='请输入密码' type="password" name="" id="password" />
						<label htmlFor="">性别</label>
						<select name="" id="" onChange={(e) => { this.changeEditValue(e, 'editSex') }} value={editSex}>
							<option value="男">男</option>
							<option value="女">女</option>
						</select>
						<label htmlFor="nickname">昵称</label><input value={editNickName} onChange={(e) => { this.changeEditValue(e, 'editNickName') }} autoComplete="off" placeholder='请输入昵称' type="text" name="" id="nickname" />
						<label htmlFor="introduction">介绍</label><textarea onChange={(e) => { this.changeEditValue(e, 'editIntroduction') }} value={editIntroduction} name="" id="introduction" cols="30" rows="10" placeholder='请输入自我介绍'></textarea>
						<label htmlFor="avator">头像</label><input onChange={() => { this.changeAvator() }} ref={c => this.fileInput = c} accept='image/*' type="file" name="" id="avator" style={{ left: "-9999px", position: "absolute" }} />
						<div className='img' onClick={() => this.fileInput.click()}>
							{imgsrc === '' ? null : <img width="100%" height="100%" src={imgsrc} alt="" />}
						</div>
						<div className='btns'>
							<div className='btn' onClick={() => { this.edit(); }}>立即修改</div>
							<div className='btn' onClick={() => { this.close(); }}>关闭</div>
						</div>
					</div>
				</div>
				<div className='info'>
					<div className='ava'>
						<img width="100%" height="100%" src={"http://localhost:3001/" + user_avator_url} alt="" />
					</div>
					<div className='mes'>
						<div className='username'>{user_nickname}</div>
						<div className='sex'>{user_sex}</div>
						<div className='introduction'>{user_introduction === '' ? '该用户很懒，没有设置用户介绍。' : user_introduction}</div>
					</div>
					<div onClick={() => this.editInfo()} className='editInfoBtn'>修改资料</div>
				</div>
				<div className='sc_content'>
					<ul className='content_tag'>
						<li onClick={() => { this.changeTab(0); }} className={activeIndex === 0 ? 'content_tag_a' : 'red'}>我的歌曲</li>
						<li onClick={() => { this.changeTab(1); }} className={activeIndex === 1 ? 'content_tag_a' : 'red'}>我的歌单</li>
						<li onClick={() => { this.changeTab(2); }} className={activeIndex === 2 ? 'content_tag_a' : 'red'}>我的MV</li>
						<li onClick={() => { this.changeTab(3); }} className={activeIndex === 3 ? 'content_tag_a' : 'red'}>我创建的歌单</li>
					</ul>
					<div className='content_co'>
						{qhTab(activeIndex, this)}
					</div>
				</div>
			</div>
		)
	}
}
